<template>

  <el-tabs :tab-position="tabPosition" style="overflow-y: auto" @tab-click="handleClick">
    <!--    基本信息-->
    <el-tab-pane label="商品基本信息填写">
      <el-form ref="form" :model="productFormData" label-width="80px">
        <el-form-item label="商品名称">
          <el-input v-model="productFormData.name"></el-input>
        </el-form-item>
        <el-form-item label="商品价格">
          <el-input v-model="productFormData.price"></el-input>
        </el-form-item>
        <el-form-item label="商品种类">
          <el-select v-model="productFormData.category"
           placeholder="请选择" @visible-change= "changeValue1( $event )">
            <el-option
              v-for="item in categoryList"
              :key="item.id"
              :label="item.category"
              :value="item.category">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品状态">
          <el-radio-group v-model="productFormData.status">
            <el-radio :label="1">上架</el-radio>
            <el-radio :label="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </el-tab-pane>
    <!--    图片上传-->
    <el-tab-pane label="图片上传">
      <el-upload
        action="http://localhost:8085/upload"
        list-type="picture-card"
        :on-success="fileSuccess"
        :on-preview="handlePictureCardPreview"
        :multiple="true"
        :on-remove="handleRemove">
        <i class="el-icon-plus"></i>
      </el-upload>
      <el-dialog :visible.sync="dialogVisible">
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>
    </el-tab-pane>
    <el-tab-pane label="商品详情">  <div id="div1"></div></el-tab-pane>
    <!--    商品添加详情确认-->
    <el-tab-pane label="确认提交" name="submit" >
      <div>
        <el-divider content-position="left">商品表单信息</el-divider>
        <el-row>
          <el-col :span="3"><div class="attrubute" >商品名称</div></el-col>
          <el-col :span="21">{{productFormData.name}}</el-col>
        </el-row>
        <el-row>
          <el-col :span="3"><div class="attrubute" >商品价格</div></el-col>
          <el-col :span="21">{{productFormData.price}}</el-col>
        </el-row>
        <el-row>
          <el-col :span="3"><div class="attrubute" >商品种类</div></el-col>
          <el-col :span="21">{{productFormData.category}}</el-col>
        </el-row>
        <el-row>
          <el-col :span="3"><div class="attrubute">商品状态</div></el-col>
          <el-col :span="21">{{productFormData.status === 1 ?"上架":"下架"}}</el-col>
        </el-row>
        <!--        图片显示-->
        <el-divider content-position="left">商品表单信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="6" v-for="pic in addBasePathUrl" :key="pic">
        <el-card>
          <el-image :src="pic" style="height: 200px;width: 200px;"></el-image>
          <el-button type="danger" @click="deleteImg(pic)">删除</el-button>
        </el-card>
          </el-col>
        </el-row>
        <!--      商品详情  -->
        <el-divider content-position="left">商品详情</el-divider>
        <el-card class="box-card" >
          <div v-html="productFormData.detail" style="height:200px; overflow: auto;"></div>
        </el-card>
        <!--        提交按钮-->
        <div style="display: flex;justify-content:flex-end;margin-top: 20px;margin-right: 20px">
          <el-button @click="submit" type="primary" >提交</el-button>
        </div>
      </div>
    </el-tab-pane>
  </el-tabs>

</template>

<script>
// 引入 wangEditor
import wangEditor from 'wangeditor';
import { request } from '@/network/request';
import { basePath } from '@/commom/commom';

export default {
  name: 'ProductEdit',
  data() {
    return {
      editor: null,
      editorData: '',
      tabPosition: 'left',
      productFormData: {
        id: '',
        name: '',
        price: '',
        status: '',
        category: '',
        imgUrl: [],
        detail: '',
      },
      addBasePathUrl: [],
      categoryList: [],
      dialogImageUrl: '',
      dialogVisible: false,
    };
  },
  created() {
    this.getProductFormData(this.$route.params.id);
  },
  mounted() {
    // eslint-disable-next-line new-cap
    const editor = new wangEditor('#div1');
    // 配置 server 接口地址
    editor.config.uploadImgServer = `${basePath}/upload`;
    // 配置 server 接口地址
    editor.config.uploadVideoServer = `${basePath}/upload`;
    editor.config.uploadVideoMaxSize = 1 * 1024 * 1024 * 1024;// 1024m
    editor.config.uploadVideoName = 'file';
    editor.config.uploadFileName = 'file';
    editor.config.uploadImgMaxSize = 2 * 1024 * 1024; // 2M
    // 配置 onchange 回调函数，将数据同步到 vue 中
    editor.config.onchange = (newHtml) => {
      this.editorData = newHtml;
    };
    editor.config.uploadImgHooks = {
      customInsert(insertImgFn, result) {
        // result 即服务端返回的接口
        console.log('customInsert', result);
        // insertImgFn 可把图片插入到编辑器，传入图片 src ，执行函数即可
        insertImgFn(`${basePath}/${result.data[0]}`);
      },
    };
    editor.config.uploadVideoHooks = {
      customInsert(insertVideoFn, result) {
        // result 即服务端返回的接口
        console.log('customInsert', result);
        // insertVideoFn 可把视频插入到编辑器，传入视频 src ，执行函数即可
        insertVideoFn(`${basePath}/${result.data[0]}`);
      },
    };
    // 创建编辑器
    editor.config.height = 700;
    editor.create();
    this.editor = editor;
  },
  methods: {
    open() {
      this.$alert(this.editor.txt.html(), {
        dangerouslyUseHTMLString: true,
      });
    },
    getProductFormData(id) {
      request({
        url: `/product/find/${id}`,
      }).then((res) => {
        if (res.code !== 200) return;
        this.productFormData = res.data;
        this.productFormData.imgUrl = res.data.imgUrl.split(',');
        for (let i = 0; i < this.productFormData.imgUrl.length; i += 1) {
          this.addBasePathUrl.push(basePath + this.productFormData.imgUrl[i]);
        }
        this.editor.txt.html(this.productFormData.detail);
      });
    },
    getEditorData() {
      // 通过代码获取编辑器内容
      this.productFormData.detail = this.editor.txt.html();
    },
    getCategory() {
      request({
        url: '/product/category',
      }).then((res) => {
        this.categoryList = res.data;
      });
    },
    handleRemove(file, fileList) {
      console.log('file', file);
      console.log('list', fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    fileSuccess(file) {
      this.productFormData.imgUrl.push(`${file.data[0]}`);
      this.addBasePathUrl.push(`${basePath}${file.data[0]}`);
    },
    handleClick(tab) {
      console.log(tab.index);
      if (tab.index === '3') {
        this.getEditorData();
      }
    },
    deleteImg(addBaseimgUrl) {
      this.addBasePathUrl = this.addBasePathUrl.filter((x) => x !== addBaseimgUrl);
      this.productFormData.imgUrl = this.productFormData.imgUrl.filter((x) => x !== addBaseimgUrl.replace(basePath, ''));
    },
    changeValue1(callback) {
      if (callback === true) {
        this.getCategory();
      }
    },
    submit() {
      for (let i = 0; i < this.categoryList.length; i += 1) {
        if (this.categoryList[i].category === this.newsFormData.category) {
          this.productFormData.categoryId = this.categoryList[i].id;
        }
      }
      this.productFormData.imgUrl = this.productFormData.imgUrl.toLocaleString();
      request({
        url: '/product/update',
        method: 'post',
        params: this.productFormData,
      }).then((res) => {
        if (res.code !== 200) return this.$message.error('用户更新失败');
        this.$router.push({ path: '/product/list' });
        return this.$message.success('用户更新成功');
      });
    },
  },
  // 不在方法体内
  beforeDestroy() {
    // 调用销毁 API 对当前编辑器实例进行销毁
    this.editor.destroy();
    this.editor = null;
  },
};
</script>

<style scoped>

.attrubute{
  height: 30px;
  background-color: #909399;
  border-radius: 20px;
  line-height: 30px;
  text-align: center;
  color: white;
  width: 100px;
  margin-bottom: 10px;
}
.el-col{
  line-height: 30px;
}
</style>
